package hkust.ee.fyp.drawer;

import hkust.ee.fyp.R;

import java.io.File;
import java.util.Calendar;

import yuku.ambilwarna.AmbilWarnaDialog;
import yuku.ambilwarna.AmbilWarnaDialog.OnAmbilWarnaListener;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;

public class DrawerActivity extends Activity implements View.OnClickListener,
		ISketchPadCallback {
	private SketchPadView m_sketchPad = null;

	private ImageButton m_stickerBtn = null;
	
		private ImageButton m_penBtn = null;
		private ImageButton m_eraserBtn = null;
		private ImageButton m_handBtn = null;
		private ImageButton m_choosePhotoframeBtn = null;
		
		private ImageButton m_pencolorBtn = null;
		private ImageButton m_pensizeBtn = null;
		private ImageButton m_undoBtn = null;
		private ImageButton m_redoBtn = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sketchpad);

		m_sketchPad = (SketchPadView) this.findViewById(R.id.sketchpad);
		
			m_stickerBtn = (ImageButton) this.findViewById(R.id.sketchpad_ImageButton_add_sticker);
	
			m_penBtn = (ImageButton) this.findViewById(R.id.sketchpad_ImageButton_pen);
			m_eraserBtn = (ImageButton) this.findViewById(R.id.sketchpad_ImageButton_eraser);
			m_handBtn = (ImageButton) this.findViewById(R.id.sketchpad_ImageButton_hand);
			m_choosePhotoframeBtn = (ImageButton) this.findViewById(R.id.sketchpad_ImageButton_choose_photoframe);
			
			m_pencolorBtn = (ImageButton) this.findViewById(R.id.sketchpad_ImageButton_pen_color);
			m_pensizeBtn = (ImageButton) this.findViewById(R.id.sketchpad_ImageButton_stroke_size);
			m_undoBtn = (ImageButton) this.findViewById(R.id.sketchpad_ImageButton_undo);
			m_redoBtn = (ImageButton) this.findViewById(R.id.sketchpad_ImageButton_redo);


		m_sketchPad.setCallback(this);
			
			m_stickerBtn.setOnClickListener(this);
			
			m_penBtn.setOnClickListener(this);			
			m_eraserBtn.setOnClickListener(this);
			m_handBtn.setOnClickListener(this);
			m_choosePhotoframeBtn.setOnClickListener(this);
			
			m_pencolorBtn.setOnClickListener(this);
			m_pensizeBtn.setOnClickListener(this);
			m_undoBtn.setOnClickListener(this);
			m_redoBtn.setOnClickListener(this);

		m_penBtn.setEnabled(false);
		
		m_redoBtn.setEnabled(false);
		m_undoBtn.setEnabled(false);

		m_sketchPad.setActivityRef( this);
		
		try{
//			Bitmap bmp = getIntent().getExtras().getParcelable("data");
			Log.d("Drawwee", getIntent().getExtras().getString("path"));
			Bitmap bmp = BitmapFactory.decodeFile(getIntent().getExtras().getString("path"));			
			m_sketchPad.setBkBitmap(bmp);			
		}
		catch( NullPointerException e ){
			
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.sketchpad_ImageButton_pen:
			onPenClick(v);
			break;

		case R.id.sketchpad_ImageButton_eraser:
			onEraseClick(v);
			break;
			
		case R.id.sketchpad_ImageButton_hand:
			onHandClick(v);
			break;
			
		case R.id.sketchpad_ImageButton_choose_photoframe:
			onChoosePhotoframe(v);
			break;

		case R.id.sketchpad_ImageButton_undo:
			onUndoClick(v);
			break;

		case R.id.sketchpad_ImageButton_redo:
			onRedoClick(v);
			break;

		case R.id.sketchpad_ImageButton_pen_color:
			onPenColorClick(v);
			break;
			
		case R.id.sketchpad_ImageButton_stroke_size:
			onPenSizeClick(v);
			break;

		case R.id.sketchpad_ImageButton_add_sticker:
			onAddStickerClick(v);
			break;
		}
	}

	protected void onPenClick(View v) {
		m_sketchPad.setStrokeType(SketchPadView.STROKE_PEN);
		m_sketchPad.enableStrokeDraw();
		
		m_penBtn.setEnabled(false);
		m_eraserBtn.setEnabled(true);
		m_handBtn.setEnabled( true);
	}

	protected void onEraseClick(View v) {
		m_sketchPad.setStrokeType(SketchPadView.STROKE_ERASER);
		m_sketchPad.enableStrokeDraw();
		
		m_penBtn.setEnabled(true);
		m_eraserBtn.setEnabled(false);
		m_handBtn.setEnabled( true);
	}
	
	protected void onHandClick(View v) {
		m_sketchPad.enableStickerDrag();

		m_penBtn.setEnabled(true);
		m_eraserBtn.setEnabled(true);
		m_handBtn.setEnabled(false);
	}
	
	protected void onChoosePhotoframe(View v) {
		Intent intent = new Intent(this, ChoosePhotoframe.class);
		/*
			Bitmap bmp = m_sketchPad.getCanvasSnapshot();
			intent.putExtra("canvas_snapshot", bmp);
		*/

		System.gc();
		startActivityForResult(intent, ACTIVITY_RESULT_CHOOSE_PHOTOFRAME);
	}

	protected void onUndoClick(View v) {
		m_sketchPad.undo();
		m_undoBtn.setEnabled(m_sketchPad.canUndo());
		m_redoBtn.setEnabled(m_sketchPad.canRedo());
	}

	protected void onRedoClick(View v) {
		m_sketchPad.redo();
		m_undoBtn.setEnabled(m_sketchPad.canUndo());
		m_redoBtn.setEnabled(m_sketchPad.canRedo());
	}
	
	protected void onPenColorClick(View v) {
		showDialog( COLOR_PICKER_DIALOG);
	}
	protected void onPenSizeClick(View v) {
		showDialog( STROKE_PICKER_DIALOG);
	}

	protected void onAddStickerClick(View v) {
		Intent intent = new Intent(this, AddSticker.class);
		startActivityForResult(intent, ACTIVITY_RESULT_ADD_STICKER);
	}

	private static final int 	ACTIVITY_RESULT_ADD_STICKER = 0,
								ACTIVITY_RESULT_CHOOSE_PHOTOFRAME = 1;
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case ACTIVITY_RESULT_ADD_STICKER:
			if (RESULT_OK == resultCode) {
				try {
					Bundle bundle = data.getExtras();
					int resource_id = bundle.getInt( "sticker_resource_id");
					Bitmap bmp = BitmapFactory.decodeResource( getResources(), resource_id);
					m_sketchPad.addStickerBitmap( bmp);
					m_sketchPad.enableStickerDrag();

					m_penBtn.setEnabled(true);
					m_eraserBtn.setEnabled(true);
					m_handBtn.setEnabled(false);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break;
			
		case ACTIVITY_RESULT_CHOOSE_PHOTOFRAME:
			if (RESULT_OK == resultCode) {
				try {
					Bundle bundle = data.getExtras();
					int resource_id = bundle.getInt( "photoframe_resource_id");
					Bitmap bmp = BitmapFactory.decodeResource( getResources(), resource_id);
					m_sketchPad.setPhotoframeBitmap( bmp);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			break;
		}
	}

	@Override
	public void onDestroy(SketchPadView obj) {
	}

	@Override
	public void onTouchDown(SketchPadView obj, MotionEvent event) {
		m_undoBtn.setEnabled(true);
	}

	@Override
	public void onTouchUp(SketchPadView obj, MotionEvent event) {
	}

	public String getStrokeFilePath() {
		File sdcarddir = android.os.Environment.getExternalStorageDirectory();
		String strDir = sdcarddir.getPath() + "/DCIM/PhotoFrame/";
		String strFileName = getStrokeFileName();
		File file = new File(strDir);
		if (!file.exists()) {
			file.mkdirs();
		}

		String strFilePath = strDir + strFileName;

		return strFilePath;
	}

	public String getStrokeFileName() {
		String strFileName = "";

		Calendar rightNow = Calendar.getInstance();
		int year = rightNow.get(Calendar.YEAR);
		int month = rightNow.get(Calendar.MONDAY);
		int date = rightNow.get(Calendar.DATE);
		int hour = rightNow.get(Calendar.HOUR);
		int minute = rightNow.get(Calendar.MINUTE);
		int second = rightNow.get(Calendar.SECOND);

		strFileName = String.format("%02d%02d%02d%02d%02d%02d.png", year,
				month, date, hour, minute, second);
		return strFileName;
	}
	
	private static final int 	COLOR_PICKER_DIALOG = 0,
								STROKE_PICKER_DIALOG = 1;
	
	protected Dialog onCreateDialog( int id)
	{		
		switch( id)
		{
			case COLOR_PICKER_DIALOG:
				final Dialog cDialog = new AmbilWarnaDialog( this, m_sketchPad.getStrokeColor(), new OnAmbilWarnaListener()
				{
					@Override
					public void onCancel(AmbilWarnaDialog dialog) {
					}

					@Override
					public void onOk(AmbilWarnaDialog dialog, int color) {
						m_sketchPad.setStrokeColor( color);
						dialog.updateColor( m_sketchPad.getStrokeColor());
					}
				});				
				return cDialog;
				
			case STROKE_PICKER_DIALOG:
				final Dialog dialog = new Dialog( this);

				dialog.setContentView(R.layout.stroke_selector);
				dialog.setTitle("Select a stroke width:");

				
				ImageButton strokeOne = (ImageButton) dialog.findViewById(R.id.stroke_ImageButton_1);
				ImageButton strokeTwo = (ImageButton) dialog.findViewById(R.id.stroke_ImageButton_2);
				ImageButton strokeThree = (ImageButton) dialog.findViewById(R.id.stroke_ImageButton_3);

				strokeOne.setOnClickListener( new ImageButton.OnClickListener()
				{

					@Override
					public void onClick(View v) {
						m_sketchPad.setPenSize( CommonDef.SMALL_PEN_WIDTH);
						dialog.dismiss();
					}
				}
				);
				
				strokeTwo.setOnClickListener( new ImageButton.OnClickListener()
				{

					@Override
					public void onClick(View v) {
						m_sketchPad.setPenSize( CommonDef.MIDDLE_PEN_WIDTH);
						dialog.dismiss();
					}
				}
				);
				
				strokeThree.setOnClickListener( new ImageButton.OnClickListener()
				{

					@Override
					public void onClick(View v) {
						m_sketchPad.setPenSize( CommonDef.LARGE_PEN_WIDTH);
						dialog.dismiss();
					}
				}
				);
				
				return dialog;
		}
		
		return null;
	}
	
	private static final int MENU_CLEAN = 0;
	private static final int MENU_CROP = 1;
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_CLEAN, 0, "Clean Strokes");
		menu.add(0, MENU_CROP, 0, "Save");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case MENU_CLEAN:
			m_sketchPad.clearAllStrokes();		
			m_redoBtn.setEnabled(false);
			m_undoBtn.setEnabled(false);
			break;
		case MENU_CROP:
			String strFilePath = getStrokeFilePath();
			Bitmap bmp = m_sketchPad.getCanvasSnapshot();
			if (null != bmp) {
				BitmapUtil.saveBitmapToSDCard(bmp, strFilePath);
			}
			break;
		}
		return true;
	}
}

class GestureListener implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {  
	SketchPadView view;  
	public GestureListener(SketchPadView view) {  
		this.view = view;  
	}
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public boolean onDoubleTap(MotionEvent e) {
		view.doubleTapAction( e);
		return false;
	}
	@Override
	public boolean onDoubleTapEvent(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public boolean onSingleTapConfirmed(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}  
}  